#!/usr/bin/env python3
# -*- coding:utf-8 -*-

from MOMA.MOMA_V1.uitls.xml_data.data_xml import Xml
from MOMA.MOMA_V1.tools.banner.banner import HeaDer
from MOMA.MOMA_V1.tools.port.nmaps import NmapMe
from MOMA.MOMA_V1.tools.whois.chinaz import Bs4_v1_ip
from MOMA.MOMA_V1.tools.whois.qichacha import Bs4_v1_url
from MOMA.MOMA_V1.tools.whois.email_skymem import Bs4_v1_email


class Core:
    def __init__(self, enterprise: str):
        self.url = None
        self.ip = "https://tool.chinaz.com/pagestatus/?url={}"
        self.enterprise = "https://www.qcc.com/web/search?key={}".format(enterprise)
        self.port_open = []
        self.email_list = []

    def get_url(self) -> str | None:
        url = Bs4_v1_url(self.enterprise).run_core()
        self.url = url
        print(self.url)
        return self.url

    def get_ip(self) -> str | None:
        self.ip = "https://tool.chinaz.com/pagestatus/?url={}".format(self.url)
        ip = Bs4_v1_ip(self.ip).run_core()
        print(ip)
        return ip

    def get_port(self, target: str) -> list | None:
        """
        扫描端口
        :param target:
        :return:
        """
        port_obj = NmapMe(target)
        self.port_open = port_obj.run_nmapme()
        print(self.port_open)
        return self.port_open

    def get_email(self, top_domain: str):
        email_url = "http://www.skymem.info/srch?q={}&ss=srch".format(top_domain)
        self.email_list = Bs4_v1_email(email_url).run_core()
        print(self.email_list)

    def get_banner(self, target_ip: str, ports: list) -> dict | None:
        """
        获取开放端口的响应信息
        :param target_ip:
        :param ports:
        :return:
        """
        banner_obj = HeaDer(target_ip, ports)
        http_res = banner_obj.run_sock()
        return self.banner_re(http_res)

    def banner_re(self, http_res) -> list | None:
        """
        使用banner特征字典与响应包对比
        最后得出服务器banner对比结果存入列表
        :param http_res:
        :return:
        """
        banner_list = []
        for xml in http_res:
            compare_obj = Xml(xml)
            file_list = compare_obj.xml_file()
            tmp = compare_obj.xml_root(file_list)
            if tmp:
                banner_list.append(tmp)
        return banner_list
